#! -*- coding:utf-8 -*-
import logging
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from pymongo import MongoClient
from django.conf import settings

_LOGGER = logging.getLogger(__name__)


# crontab 启动 每十五分钟运行一次
class Command(BaseCommand):
    def handle(self, **options):
        _LOGGER.info('gen_channel_data_point start')
        # now = datetime(2019, 05, 04, 00, 00, 00)  # 获取东八区（北京）时间
        now = datetime.utcnow() + timedelta(hours=8)  # 获取东八区（北京）时间

        create_time = datetime.strptime("{}-{}-{} {}:{}:0".format(now.year, now.month, now.day, now.hour, now.minute),
                                        "%Y-%m-%d %H:%M:%S")
        start = datetime.strptime("{}-{}-{} 0:0:0".format(now.year, now.month, now.day), "%Y-%m-%d %H:%M:%S")
        if now.hour == 0 and now.minute < 5:
            # 如果时间在 00:00 - 00:05 执行，统计昨天的数据
            end = start
            start = (start - timedelta(days=1))
        else:
            end = (start + timedelta(days=1))

        self.cal_stats(start, end, create_time)

    def cal_stats(self, start, end, create_time):
        query_dct = {}
        query_dct['start'] = {}
        query_dct['start']['$gte'] = start
        query_dct['start']['$lt'] = end
        mg = MongoClient(settings.MONGO_ADDR).paychannel_stat
        items = mg.channel_status.find(query_dct)

        print("gen_channel_data_point query_dct %s" % query_dct)
        for o in items:
            d = {}
            d['mch_id'] = o['mch_id']
            d['channel_id'] = o['channel_id']
            d['total_count'] = o['total_count']
            d['channel_name'] = o['channel_name']
            d['service_name'] = o['service_name']
            d['count'] = o['count']
            d['total'] = o['total']
            d['create_time'] = create_time
            mg.data_point_fix.insert_one(d)
        _LOGGER.info('gen_channel_data_point end')
